#include "mode_preservation.h"
#include "main_motor.h"
#include "actuator_control.h"
#include "timer_utils.h"

// 保鲜模式内部状态
static struct {
    uint32_t mixer_timer;
    bool mixer_active;
} s_preserve_state;

// 保鲜模式进入
void preservation_mode_enter(ModeConfig* config) {
    memset(&s_preserve_state, 0, sizeof(s_preserve_state));
    
    // 初始化电机配置（保鲜模式下电机很少运行）
    MotorConfig motor_cfg = {
        .min_current = config->cooling_min_current,
        .max_current = config->cooling_max_current,
        .start_timeout = 5000,
        .retry_count = 3,
        .protection_time = 30000
    };
    motor_init(&motor_cfg);
    
    s_preserve_state.mixer_timer = get_system_time_ms();
    s_preserve_state.mixer_active = false;
    
    printf("Entering preservation mode\n");
}

// 保鲜模式处理
void preservation_mode_process(ModeConfig* config, SensorData* sensors, DeviceState* state) {
    uint32_t current_time = get_system_time_ms();
    
    // 温度控制
    if (sensors->material_temp > config->preservation_target + config->preservation_hyst) {
        if (!state->comp_running) {
            actuator_set_compressor(true);
            actuator_set_precool_valve(true);
            state->comp_running = true;
            state->precool_valve = true;
        }
    } else if (sensors->material_temp < config->preservation_target - config->preservation_hyst) {
        if (state->comp_running) {
            actuator_set_compressor(false);
            actuator_set_precool_valve(false);
            state->comp_running = false;
            state->precool_valve = false;
        }
    }
    
    // 搅拌机控制（每5分钟运行1分钟）
    if (current_time - s_preserve_state.mixer_timer > 60000) {  // 1分钟检查一次
        s_preserve_state.mixer_timer = current_time;
        
        uint32_t elapsed_min = state->mode_runtime / 60;
        // 每5分钟的第1分钟运行
        if (elapsed_min % 5 == 0) {
            if (!s_preserve_state.mixer_active) {
                actuator_set_mixer(true);
                state->mixer_running = true;
                s_preserve_state.mixer_active = true;
            }
        } else {
            if (s_preserve_state.mixer_active) {
                actuator_set_mixer(false);
                state->mixer_running = false;
                s_preserve_state.mixer_active = false;
            }
        }
    }
    
    // 保鲜模式下旁通阀关闭
    state->bypass_valve = false;
    state->cooling_valve = false;
    state->motor_running = false;
    state->pump_running = false;
}

// 保鲜模式退出
void preservation_mode_exit(void) {
    actuator_set_compressor(false);
    actuator_set_precool_valve(false);
    actuator_set_mixer(false);
    
    printf("Exiting preservation mode\n");
}
